package com.lineng.service.impl;

import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.lineng.dao.HomeMapper;
import com.lineng.pojo.Home;
import com.lineng.service.HomeService;
import com.lineng.util.FileUtils;
import com.lineng.util.UrlUtil;
import com.lineng.util.VerificationUtil;

@Service
public class HomeServiceImpl implements HomeService {

	@Autowired
	HomeMapper homeMapper;

	@Autowired
	private HttpServletRequest request;

	public List<Home> getHome() {

		return homeMapper.selectByExample(null);
	}

	public int updateHome(Home home, MultipartFile file) {
		int num = 0;
		// 权限验证，判断用户是否有权限更改
		if (VerificationUtil.verification(request) == 1) {
			// 获得项目的路径
			ServletContext sc = request.getSession().getServletContext();
			// 上传位置
			String path = sc.getRealPath("/") + home.getPath(); // 设定文件保存的目录
			if (file != null) {
				try {
					FileUtils.saveFile(file, path, 2600, 1750);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			if (home != null) {
				home.setDate(new Date());
				// 判断连接是否带有http，如果没有就把https拼接上
				if (home.getUrl().startsWith("http")) {
					num = homeMapper.updateByPrimaryKeySelective(home);
				} else {
					home.setUrl(UrlUtil.url(home.getUrl()));
					num = homeMapper.updateByPrimaryKeySelective(home);
				}
			}
			return num;
		}
		return num;

	}

}
